//
//  IdentifyViewController.swift
//  WangPu
//
//  Created by xiaozhi on 15/10/23.
//  Copyright © 2015年 zhixiao. All rights reserved.
//

import UIKit

class IdentifyViewController: BaseViewController {
    var nameField:UITextField!
    var identfyField:UITextField!
    var imageFont:UIImageView!
    var imageback:UIImageView!
    var commitBtn:UIButton!
    var currentBtn:UIButton?
    var IdentifySuccess:(()->Void)?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "实名认证"
        let backItem = UIBarButtonItem(image: UIImage(named: "back_icon"), style:UIBarButtonItemStyle.Plain, target:self, action:"goBack")
        backItem.tintColor = UIColor.whiteColor()
        self.navigationItem.leftBarButtonItem = backItem
        self.automaticallyAdjustsScrollViewInsets = false
        view.backgroundColor = commonBackgoundColor
        // Do any additional setup after loading the view.
        //真实姓名
        //receiver-icon1
        let baseHieght:CGFloat = 40.0
        let labelX:CGFloat = 32.0
        let offsetX:CGFloat = 10.0
        let line1 = UIView(frame: CGRectMake(0, 74, view.bounds.size.width, baseHieght))
        line1.backgroundColor = UIColor.whiteColor()
        let userImgView = UIImageView(frame: CGRectMake(offsetX, (line1.bounds.size.height-16)/2.0, 15, 18))
        userImgView.image = UIImage(named: "user")
        line1.addSubview(userImgView)
        let note1 = UILabel(frame: CGRectMake(labelX, 0, 75, baseHieght))
        note1.text = "真实姓名："
        note1.font = UIFont.systemFontOfSize(14)
        line1.addSubview(note1)
        nameField = UITextField(frame: CGRectMake(CGRectGetMaxX(note1.frame), 0, line1.bounds.size.width - CGRectGetMaxX(note1.frame), baseHieght))
        nameField.borderStyle = UITextBorderStyle.None
        nameField.placeholder = "请输入姓名"
        nameField.font = UIFont.systemFontOfSize(14)
        nameField.delegate = self
        line1.addSubview(nameField)
        view.addSubview(line1)
        //身份证号
        // phone-icon2
        let line2 = UIView(frame: CGRectMake(0, CGRectGetMaxY(line1.frame)+10, view.bounds.size.width, baseHieght))
        line2.backgroundColor = UIColor.whiteColor()
        let phoneImgView = UIImageView(frame: CGRectMake(offsetX, (line2.bounds.size.height-16)/2.0, 16, 16))
        phoneImgView.image = UIImage(named: "real_name")
        line2.addSubview(phoneImgView)
        let note2 = UILabel(frame: CGRectMake(labelX, 0, 75, baseHieght))
        note2.text = "身份证号："
        note2.font = UIFont.systemFontOfSize(14)
        line2.addSubview(note2)
        identfyField = UITextField(frame: CGRectMake(CGRectGetMaxX(note1.frame), 0, line1.bounds.size.width - CGRectGetMaxX(note1.frame), baseHieght))
        identfyField.borderStyle = UITextBorderStyle.None
        identfyField.placeholder = "请填写身份证号"
        identfyField.font = UIFont.systemFontOfSize(14)
        identfyField.delegate = self
        line2.addSubview(identfyField)
        view.addSubview(line2)
        
        //提示一
        let star1 = UILabel(frame: CGRectMake(offsetX, CGRectGetMaxY(line2.frame)+8, 12, 16))
        star1.textColor = commonRedColor
        star1.font = UIFont.systemFontOfSize(13)
        star1.text = "*"
        view.addSubview(star1)
        let info1 = UILabel(frame: CGRectMake(22, CGRectGetMaxY(line2.frame)+8, 200, 20))
//        note1.textColor = commonRedColor
        info1.font = UIFont.systemFontOfSize(13)
        info1.textColor = UIColor.darkGrayColor()
        info1.text = "请上传身份证的正反两面"
        view.addSubview(info1)
        //imageview
        let distance:CGFloat = (view.bounds.size.width - 220)/3.0
        imageFont = UIImageView(frame: CGRectMake(distance, CGRectGetMaxY(info1.frame)+15, 110, 110))
        imageFont.backgroundColor = UIColor.whiteColor()
        imageFont.layer.cornerRadius = 3.0
        view.addSubview(imageFont)
        let buttonFont = UIButton(frame: CGRectInset(imageFont.frame, -1, -1))
        buttonFont.setBackgroundImage(UIImage(named: "false_fang"), forState: UIControlState.Normal)
        buttonFont.setBackgroundImage(UIImage(named: "false_fang"), forState: UIControlState.Highlighted)
        buttonFont.addTarget(self, action: "fontButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        buttonFont.tag = 1
        view.addSubview(buttonFont)
        
        imageback = UIImageView(frame: CGRectMake(CGRectGetMaxX(imageFont.frame)+distance, CGRectGetMaxY(info1.frame)+15, 110, 110))
        imageback.backgroundColor = UIColor.whiteColor()
        imageback.layer.cornerRadius = 3.0
        view.addSubview(imageback)
        let buttonBack = UIButton(frame: CGRectInset(imageback.frame, -1, -1))
        buttonBack.setBackgroundImage(UIImage(named: "false_fang"), forState: UIControlState.Normal)
        buttonBack.setBackgroundImage(UIImage(named: "false_fang"), forState: UIControlState.Highlighted)
        buttonBack.addTarget(self, action: "backButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        buttonBack.tag = 2
        view.addSubview(buttonBack)

        //提交按钮
        //新建
        commitBtn = UIButton(frame: CGRectMake(25,CGRectGetMaxY(imageFont.frame)+30, view.bounds.size.width - 50, 40))
        commitBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        commitBtn.setTitle("确认提交", forState: UIControlState.Normal)
        commitBtn.backgroundColor = commonRedColor
        commitBtn.addTarget(self, action: "commitButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        commitBtn.layer.cornerRadius = 4.0
        commitBtn.titleLabel?.font = UIFont.systemFontOfSize(15)
        view.addSubview(commitBtn)
        
        //info2
        let star2 = UILabel(frame: CGRectMake(offsetX, CGRectGetMaxY(commitBtn.frame)+8, 12, 24))
        star2.font = UIFont.systemFontOfSize(13)
        star2.text = "*"
        view.addSubview(star2)
        let info2 = UILabel(frame: CGRectMake(22, CGRectGetMaxY(commitBtn.frame)+8, view.bounds.size.width-28, 40))
        //        note1.textColor = commonRedColor
        info2.font = UIFont.systemFontOfSize(13)
        info2.numberOfLines = 0
        info2.textColor = UIColor.darkGrayColor()
        info2.text = "海关需对海外购物查验身份信息，错误信息可能导致无法正常通关。"
        view.addSubview(info2)
        //info3
        let star3 = UILabel(frame: CGRectMake(offsetX, CGRectGetMaxY(info2.frame), 12, 24))
        star3.font = UIFont.systemFontOfSize(13)
        star3.text = "*"
        view.addSubview(star3)
        let info3 = UILabel(frame: CGRectMake(22, CGRectGetMaxY(info2.frame), view.bounds.size.width-28, 30))
        info3.numberOfLines = 0
        //        note1.textColor = commonRedColor
        info3.font = UIFont.systemFontOfSize(13)
        info3.textColor = UIColor.darkGrayColor()
        info3.text = "身份信息将加密报关，旺铺将保证您的信息安全。"
        view.addSubview(info3)
    }
    func fontButtonClick(button:UIButton)->Void{
        currentBtn = button
        let alertController = UIAlertController(title: "身份证正面照片", message: "", preferredStyle: UIAlertControllerStyle.ActionSheet)
        let takePhotoAction = UIAlertAction(title: "拍照", style: UIAlertActionStyle.Destructive){ action in
            let imagePick = UIImagePickerController()
            imagePick.delegate = self
            imagePick.allowsEditing = true
            imagePick.sourceType = UIImagePickerControllerSourceType.Camera
            imagePick.videoQuality = UIImagePickerControllerQualityType.TypeMedium
            self.presentViewController(imagePick, animated: true, completion: nil)
            
        }
        let imageLibAction = UIAlertAction(title: "照片", style: UIAlertActionStyle.Default){ action in
            let imagePick = UIImagePickerController()
            imagePick.delegate = self
            imagePick.allowsEditing = true
            imagePick.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
            self.presentViewController(imagePick, animated: true, completion: nil)
        }
        let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
        
        alertController.addAction(cancelAction)
        alertController.addAction(imageLibAction)
        alertController.addAction(takePhotoAction)
        self.presentViewController(alertController, animated: true, completion: nil)
    }
    func backButtonClick(button:UIButton)->Void{
        currentBtn = button
        let alertController = UIAlertController(title: "身份证反面照片", message: "", preferredStyle: UIAlertControllerStyle.ActionSheet)
        let takePhotoAction = UIAlertAction(title: "拍照", style: UIAlertActionStyle.Destructive){ action in
            let imagePick = UIImagePickerController()
            imagePick.delegate = self
            imagePick.allowsEditing = true
            imagePick.sourceType = UIImagePickerControllerSourceType.Camera
            imagePick.videoQuality = UIImagePickerControllerQualityType.TypeMedium
            self.presentViewController(imagePick, animated: true, completion: nil)
            
        }
        let imageLibAction = UIAlertAction(title: "照片", style: UIAlertActionStyle.Default){ action in
            let imagePick = UIImagePickerController()
            imagePick.delegate = self
            imagePick.allowsEditing = true
            imagePick.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
            self.presentViewController(imagePick, animated: true, completion: nil)
        }
        let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
        
        alertController.addAction(cancelAction)
        alertController.addAction(imageLibAction)
        alertController.addAction(takePhotoAction)
        self.presentViewController(alertController, animated: true, completion: nil)
    }
    func commitButtonClick()->Void{
        if let name = self.nameField.text{
            let nameinfo = name.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) as NSString
            if nameinfo.length == 0{
                self.showTips("真实姓名不能为空")
                return
            }
        }
        else{
            self.showTips("真实姓名不能为空")
            return
        }
        if let name = self.identfyField.text{
            let nameinfo = name.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) as NSString
            if nameinfo.length == 0{
                self.showTips("身份证不能为空")
                return
            }
        }
        else{
            self.showTips("身份证不能为空")
            return
        }
        if imageFont.image == nil || imageback.image == nil{
            self.showTips("请选择好图片")
            return
        }
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        let data1:NSData? = UIImagePNGRepresentation(imageFont.image!)
        let data2:NSData? = UIImagePNGRepresentation(imageback.image!)
        if data1 == nil || data2 == nil{
             self.showTips("错误的图片格式")
            return
        }
        parameters.setObject(self.nameField.text!, forKey: "realname")
        parameters.setObject(self.identfyField.text!, forKey: "dentity")
        parameters.setObject(data1!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength), forKey: "id_photo_opposite")
        parameters.setObject(data2!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength), forKey: "id_photo_positive")
        request.requestStart("/checkout/setReal", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()){
                self.hiddenProcessView()
            }
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                    dispatch_async(dispatch_get_main_queue()){
                        self.showTips("数据加载出错")
                    }
                    return
                }
                if (dic?["result"])! as! String == "0"{
                    dispatch_async(dispatch_get_main_queue()){
                        self.showTips("认证成功"){
                            GlobalDataHelper.instance.is_authentication = "0"
                            self.IdentifySuccess?()
                            self.navigationController?.popViewControllerAnimated(true)
                        }
                    }
                }
                dispatch_async(dispatch_get_main_queue()){
                }
            }
            else{
                self.showTips("加载失败")
            }
        })
        self.showProcess("加载中...")
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func  goBack(){
        self.navigationController?.popViewControllerAnimated(true)
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
extension IdentifyViewController:UITextFieldDelegate{
    func textFieldDidBeginEditing(textField: UITextField){
    }
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}
extension IdentifyViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){
        print(info[UIImagePickerControllerMediaType])
        let image = info[UIImagePickerControllerEditedImage] as! UIImage
        if currentBtn?.tag == 1{
            imageFont.image = image.scaleTosize(CGSizeMake(400, 300))
        }
        else{
             imageback.image = image.scaleTosize(CGSizeMake(400, 300))
        }
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController){
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}